//
//  HTOrderLinesViewController.m
//  TruckDriver
//
//  Created by Ting Han on 2017/9/26.
//  Copyright © 2017年 Ting Han. All rights reserved.
//

#import "HTOrderLinesViewController.h"
#import "HTVoiceRemindCell.h"
#import "HTOrderLineCell.h"
#import "HTAddOrderCell.h"
#import "HTOrderLineModel.h"
#import "UIAlertController+Constructor.h"

//线路详情
#import "HTOrderLineDetialViewController.h"
//添加线路
#import "HTAddOrderLineViewController.h"

@interface HTOrderLinesViewController ()<UITableViewDelegate,UITableViewDataSource,HTAddOrderLineViewControllerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataSource;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *safeBottomHeight;



@end
static NSString *orderLineCell = @"orderLineCell";


@implementation HTOrderLinesViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configTableView];
    
}
- (void)configTableView{
    self.safeBottomHeight.constant = IPHONE_SAFEBOTTOMAREA_HEIGHT; self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"HTOrderLineCell" bundle:nil] forCellReuseIdentifier:orderLineCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"HTAddOrderCell" bundle:nil] forCellReuseIdentifier:addOrderCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"HTVoiceRemindCell" bundle:nil] forCellReuseIdentifier:voiceCell];
    self.tableView.backgroundColor = kBackgroundColor;
    [self configTableHeader];
    self.tableView.mj_header = self.header;
  
}

- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

#pragma mark --- tableViewDelegate & dataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }
    return self.dataSource.count + 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {//voice
        return 59.f;
    }else{
        if (indexPath.row == self.dataSource.count) {//add
            return kFooterHeight;
        }
        return 86.f;//normal
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        return 20.f;
    }
    return 0.f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
       HTVoiceRemindCell *cell = [tableView dequeueReusableCellWithIdentifier:voiceCell forIndexPath:indexPath];
        cell.voiceSwitch.on = [HTMUserDefaultUtil getPlayMusicFlag];
        [cell.voiceSwitch addTarget:self action:@selector(swichAction:) forControlEvents:UIControlEventValueChanged];
        return cell;
    }else{
        if (indexPath.row == self.dataSource.count) {
            HTAddOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:addOrderCell forIndexPath:indexPath];
            [cell.addBtn addTarget:self action:@selector(addOrderLine:) forControlEvents:UIControlEventTouchUpInside];
            return cell;
        }else{
            HTOrderLineCell *cell = [tableView dequeueReusableCellWithIdentifier:orderLineCell forIndexPath:indexPath];
            cell.lineModel = self.dataSource[indexPath.row];
            return cell;
        }
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]initWithFrame:tableView.tableHeaderView.bounds];
    view.backgroundColor = kBackgroundColor;
    return view;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.tableView)
    {
        CGFloat sectionHeaderHeight = 20;
        if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
        }
    }
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return NO;
    }
    if (indexPath.row == self.dataSource.count) {
        return NO;
    }
    return YES;
}
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    [UIAlertController alertStyleShowInController:self title:@"温馨提示" message:@"是否删除此线路" alertActionsBlock:^(NSMutableArray<UIAlertAction *> *alertActions) {
        [alertActions addObject:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [alertActions addObject:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self netDeleteDataModel:self.dataSource[indexPath.row]indexPath:indexPath];
           
        }]];
    } completion:^{
        
    }];
}

#pragma mark --- 点击事件

//添加线路
- (void)addOrderLine:(UIButton *)sender{
    
    HTAddOrderLineViewController *add = [[HTAddOrderLineViewController alloc]init];
    add.delegate = self;
    [self.navigationController pushViewController:add animated:YES];
    
}
- (void)swichAction:(UISwitch *)sender{
    BOOL isButtonOn = [sender isOn];
    [HTMUserDefaultUtil savePlayMusicFlag:isButtonOn];
    HTVoiceRemindCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    if (isButtonOn) {
        //开
        cell.messageStr = @"货源声音提醒(已开启)";
    }else {
        //关
        cell.messageStr = @"货源声音提醒(已关闭)";
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 || indexPath.row == self.dataSource.count) {
        return;
    }
    HTOrderLineDetialViewController *detial = [[HTOrderLineDetialViewController alloc]init];
    detial.lineModel = self.dataSource[indexPath.row];
    [self.navigationController pushViewController:detial animated:YES];
}
- (void)didClickConform{
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark --- 网络请求数据
- (void)loadNewData{
    [self netLoadData];
}
- (void)netLoadData{
    [HTHttpRequestManager requestLinesListSuccess:^(id  _Nullable responseObject) {
        DBLog(@"列表：%@",responseObject);
        if (!responseObject) {
            [HTShowUtil showMessage:@"列表请求错误"];
            return;
        }
        NSString *codeStr = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        if (![codeStr isEqualToString:@"200"]) {
            [HTShowUtil showMessage:@"列表请求错误"];
            return;
        }
        [self.dataSource removeAllObjects];
        self.dataSource = [HTOrderLineModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"data"]];
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSError * _Nonnull error) {
         [self.tableView.mj_header endRefreshing];
         [HTShowUtil showMessage:@"网络错误"];
    }];
}
- (void)netDeleteDataModel:(HTOrderLineModel *)model indexPath:(NSIndexPath *)indexPath{
    [self startHud];
    [HTHttpRequestManager requestDeletelinesWithId:model.ID success:^(id  _Nullable responseObject) {
        [self endHud];
        if (!responseObject) {
            [HTShowUtil showMessage:@"删除线路失败"];
            return;
        }
        NSString *codeStr = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        if (![codeStr isEqualToString:@"200"]) {
            [HTShowUtil showMessage:@"删除线路失败"];
            return;
        }
        [HTShowUtil showMessage:@"删除线路成功"];
        [self.dataSource removeObjectAtIndex:indexPath.row];
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    } failure:^(NSError * _Nonnull error) {
        [self endHud];
        [HTShowUtil showMessage:@"网络错误"];
    }];
}

@end
